package com.ylsf.blog.service.impl;

import com.ylsf.blog.mapper.UserMapper;
import com.ylsf.blog.pojo.User;
import com.ylsf.blog.service.SubmitService;
import com.ylsf.blog.utils.SqlSessionUtil;
import org.apache.ibatis.session.SqlSession;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * 注册服务实现类
 */
public class SubmitServiceImpl implements SubmitService {
    @Override
    public boolean judgeUsername(String username) {
        //用户名长度在4到16个字符之间,只能包括大小写字母、数字和下划线
        // 用户名正则表达式
        String usernameRegex = "^[\u4e00-\u9fa5a-zA-Z0-9_]{2,16}$";

        // 创建Pattern对象
        Pattern usernamePattern = Pattern.compile(usernameRegex);

        // 创建Matcher对象
        Matcher usernameMatcher = usernamePattern.matcher(username);
        if(usernameMatcher.matches()){
            return true;
        }
        return false;
    }

    @Override
    public boolean judgePassword(String password) {
        //至少包含一个数字，至少包含一个小写字母，至少包含一个大写字母，密码长度在8到20个字符之间
        // 用户名正则表达式
        String passwordRegex = "^[a-zA-Z0-9_]{8,16}$";

        // 创建Pattern对象
        Pattern passwordPattern = Pattern.compile(passwordRegex);

        // 创建Matcher对象
        Matcher passwordMatcher = passwordPattern.matcher(password);
        if(passwordMatcher.matches()){
            return true;
        }
        return false;
    }

    @Override
    public boolean submitUsernamePwd(String username, String password) {
        SqlSession sqlSession = SqlSessionUtil.openSession();
        UserMapper userMapper = sqlSession.getMapper(UserMapper.class);
        boolean flag=false;
        try {
            Integer integer = userMapper.insertUser(new User(username, password, 1));
            if (integer != 0) {
                flag=true;
            }
            sqlSession.commit();
        }
        catch (Exception e){
            if (sqlSession != null) {
                sqlSession.rollback(); // 在catch块中进行回滚操作
            }
        }finally {
            if (sqlSession != null) {
                SqlSessionUtil.close(sqlSession); // 在finally块中关闭SqlSession
            }
        }
        return flag;
    }
}
